package com.atlbb.controller;

import com.atlbb.mybatis.entity.User;
import com.atlbb.service.UserService;
import com.atlbb.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiangQingBin
 * @version 1.00
 * @ClassName UserController
 * @Description TODO
 * @time 2021/11/7 15:26
 */
@RestController//由于是vue前后端分离项目，所有我们返回的就是json格式的数据，不使用Controller
@CrossOrigin//解决跨域的相关注解，使得vue的axios可以请求数据
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    
    @GetMapping("/findAll")
    public List<User> findAll() {
        System.out.println("请求findAll");
        return userService.findAll();
    }
    
    //保存用户
    @PostMapping("/saveOne")
    public Result saveOne(@RequestBody User user){
        Result result = new Result();
        try {
                userService.saveOne(user);
                result.setMsg("添加成功！");
        } catch (Exception e) {
            result.setStatue(false);
            result.setMsg("操作失败！");
        }
        return result;
    }
    //使用RequestBody来接受一个User对象
    @PostMapping("/updateOne")
    public Result saveOrUpdateOne(@RequestBody User user) {
        //设置一个Result来显示是否操作成功
        Result result = new Result();
        try {
//
                userService.updateOne(user);
                result.setMsg("编辑成功！");
            
        } catch (Exception e) {
            result.setStatue(false);
            result.setMsg("操作失败！");
        }
        return result;
    }
    
    //根据id删除一个用户
    @GetMapping("/deleteOneById")
    public Result deleteOneById(@RequestParam("id") Integer id) {
        Result result = new Result();
        try {
            userService.deleteOneById(id);
            result.setMsg("删除成功！");
        } catch (Exception e) {
            result.setStatue(false);
            result.setMsg("删除失败！");
        }
        return result;
    }
    
    //查询所有
    @GetMapping("/findTotal")
    public long findTotal() {
        return userService.findCount();
    }
    
    //分页查询
//    @GetMapping("/findByPage")
//    public Map<String, Object> findByPage(@RequestParam("pageNow") Integer pageNow, @RequestParam("pageSize") Integer pageSize) {
//        pageNow = pageNow == null ? 1 : pageNow;
//        pageSize = pageSize == null ? 4 : pageSize;
//        HashMap<String, Object> results = new HashMap<>();
//        pageNow = (pageNow-1)*pageSize;
//        List<User> users = userService.findByPage(pageNow, pageSize);
//        Long total = userService.findCount();
//        results.put("total", total);
//        results.put("users", users);
//        return results;
//    }

}
